package com.ygp.lock.rlock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <Description> <br>
 *
 * @author linmiaolai@sanyygp.com<br>
 * @version 1.0<br>
 * @date 2021/11/16 <br>
 */
@Slf4j(topic = "c.FairLockTest")
public class FairLockTest {
    ReentrantLock unFairLock = new ReentrantLock(false);
    ReentrantLock fair = new ReentrantLock(true);

    public static void main(String[] args) throws InterruptedException {
        new FairLockTest().unFair();
//        new FairLockTest().fair();
    }

    public void unFair() throws InterruptedException {
        unFairLock.lock();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                unFairLock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    unFairLock.unlock();
                }
            }, "t" + i).start();
        }

        // 1s 之后去争抢锁
        Thread.sleep(3000);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start...");
            unFairLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " running...");
            } finally {
                unFairLock.unlock();
            }
        }, "强行插入").start();
        unFairLock.unlock();
    }

    public void fair() throws InterruptedException {
        fair.lock();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                fair.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    fair.unlock();
                }
            }, "t" + i).start();
        }

        // 1s 之后去争抢锁
        Thread.sleep(3000);
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start...");
            fair.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " running...");
            } finally {
                fair.unlock();
            }
        }, "强行插入").start();
        fair.unlock();
    }
}
